<template>
  <div class="site-overview">
    <div class="site-add">
      <el-button type="primary" @click="handleAddSite">添加站点</el-button>
      <div class="change-card">
        <el-tooltip content="卡片模式" placement="bottom" effect="light">
          <a :class="{ active: showCard }" href="javascript:;" @click="showCard = true"><i class="iconfont">&#xe6c9;</i></a>
        </el-tooltip>
        <el-tooltip content="列表模式" placement="bottom" effect="light">
          <a :class="{ active: !showCard }" href="javascript:;" @click="showCard = false"><i class="iconfont">&#xe6ca;</i></a>
        </el-tooltip>
      </div>
    </div>
    <div v-if="currentTabInfo">
      <div v-if="showCard" class="site-card">
        <div class="overview-info">
          <el-tabs v-model="currentTabIndex" type="card">
            <el-tab-pane v-for="(item, index) in siteList" :key="item.id" :label="item.name" :name="index"></el-tab-pane>
          </el-tabs>
          <div class="overview-info-card">
            <div class="row1">
              <span class="site-name">{{ currentTabInfo.name }}</span>
              <el-popover placement="right" title="编辑站点名称" :width="350" trigger="click" ref="editPopoverRef" @show="handlePopShow" @hide="handlePopHide">
                <template #reference>
                  <el-icon :size="16"><Edit /></el-icon>
                </template>
                <div class="site-edit-box">
                  <el-input v-model="currentSiteName" placeholder="输入站点名称" style="margin-bottom: 10px" />
                  <el-button size="small" type="primary" @click="handleEditSiteName">确认</el-button>
                  <el-button size="small" @click="editPopoverRef?.hide()">取消</el-button>
                </div>
              </el-popover>
              <span class="site-status">
                <span class="site-status-tag" :class="'tag-' + currentTabInfo.state">{{ siteStatus.find(e => e.value == currentTabInfo.state)?.label }}</span>
              </span>
            </div>
            <div class="row2" @click="handleOpenSite">
              <span class="site-url">{{ currentTabInfo.domain + currentTabInfo.uri }}</span>
              <el-icon class="site-url-icon"><Link /></el-icon>
            </div>
            <div class="row3">
              <div class="row3-left">
                <div class="site-info-item">
                  <el-icon><Clock /></el-icon>
                  <span class="label">创建时间</span>
                  <span class="value">{{ currentTabInfo.createTime }}</span>
                </div>
                <div class="site-info-item">
                  <el-icon><Clock /></el-icon>
                  <span class="label">更新时间</span>
                  <span class="value">{{ currentTabInfo.updateTime }}</span>
                </div>
                <div class="site-info-item">
                  <el-icon><Cpu /></el-icon>
                  <span class="label">运行时间</span>
                  <span class="value">{{ dayjs(currentTabInfo.updateTime).diff(dayjs(currentTabInfo.createTime), 'day') }}天</span>
                </div>
              </div>
              <div class="row3-divider"></div>
              <div class="row3-right"></div>
            </div>
            <div class="row4">
              <el-button type="primary" @click="goSiteBuild(currentTabInfo)">网站建设</el-button>
              <el-button v-if="hasPermission(['site:overview:edit']) && !currentTabInfo.isAsh" @click="handleAshSite(currentTabInfo)">置灰</el-button>
              <el-button v-if="hasPermission(['site:overview:edit']) && currentTabInfo.isAsh" @click="handleUnAshSite(currentTabInfo)">取消置灰</el-button>
              <!-- <el-button v-if="hasPermission(['site:overview:delete'])" @click="handleDeleteSite(currentTabInfo)">删除</el-button> -->
              <el-button v-if="hasPermission(['site:overview:edit']) && currentTabInfo.state == 0" @click="handleUpdateState(1)">关停</el-button>
              <el-button v-if="hasPermission(['site:overview:edit']) && currentTabInfo.state == 1" @click="handleUpdateState(0)">启用</el-button>
            </div>
          </div>
        </div>
        <div class="more-info">
          <el-tabs v-model="currentMoreTabName">
            <el-tab-pane label="基础信息" name="base">
              <BaseInfo :form="currentTabInfo" @update="handleGetSiteList" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <div v-else class="site-list">
        <RuifoxTable v-loading="siteListLoading" v-model:tableData="siteList" :field-list="fieldList" :default-index="true">
          <!-- 站点链接 -->
          <template #url="{ element }">
            <a :href="element.url" target="_blank">{{ element.domain + element.uri }}</a>
          </template>
          <!-- 站点图标 -->
          <template #logo="{ element }">
            <img :src="element.logo" alt="" />
          </template>
          <!-- 状态 -->
          <template #state="{ element }">
            <el-tag v-if="element.state == 1" type="info">已关停</el-tag>
            <el-tag v-else>运行中</el-tag>
          </template>
          <!-- 置灰状态 -->
          <template #isAsh="{ element }">
            <el-tag v-if="element.isAsh" type="info">已置灰</el-tag>
            <el-tag v-else type="success">未置灰</el-tag>
          </template>
          <!-- 操作列 -->
          <template #options="{ element }">
            <div class="table-td-option unmover">
              <el-button v-if="hasPermission(['site:overview:edit']) && element.state == 0" link type="primary" size="small" @click="handleUpdateState(1)">关停</el-button>
              <el-button v-if="hasPermission(['site:overview:edit']) && element.state == 1" link type="primary" size="small" @click="handleUpdateState(0)">启用</el-button>
              <el-button type="primary" size="small" link @click="goSiteBuild(element)">建设中心</el-button>
              <el-button v-if="hasPermission(['site:overview:edit'])" type="primary" size="small" link @click="handleEditSite(element)">编辑</el-button>
              <el-dropdown trigger="click">
                <i class="iconfont">&#xe78d;</i>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <span v-if="hasPermission(['site:overview:delete'])" @click="handleDeleteSite(element)">删除</span>
                      <span v-if="hasPermission(['site:overview:edit']) && !element.isAsh" @click="handleDeleteSite(element)">置灰</span>
                      <span v-if="hasPermission(['site:overview:edit']) && element.isAsh" @click="handleDeleteSite(element)">取消置灰</span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </RuifoxTable>
      </div>
    </div>
    <el-empty v-else description="暂无站点，请添加"></el-empty>
    <el-dialog v-model="isShowForm" :title="siteForm.id ? '修改站点' : '添加站点'" width="40%" @close="siteDialogClose" class="site-dialog">
      <el-scrollbar height="500px">
        <el-form :model="siteForm" :rules="siteFormRules" label-width="110px" label-position="right" ref="siteFormRef">
          <el-form-item label="站点名称" prop="name">
            <el-input v-model="siteForm.name" placeholder="输入站点名称" />
          </el-form-item>
          <el-form-item label="静态域名" prop="domain">
            <el-input v-model="siteForm.domain" placeholder="输入静态域名" />
          </el-form-item>
          <el-form-item label="uri" prop="uri">
            <el-input v-model="siteForm.uri" placeholder="输入uri" />
          </el-form-item>
          <el-form-item label="站点图标">
            <div class="form-item">
              <div class="site-ico-box">
                <div class="site-ico" v-if="siteForm.logo">
                  <img :src="siteForm.logo" alt="" />
                </div>
                <el-button link type="primary" v-if="siteForm.logo" @click="handleUploadLogo">重新上传</el-button>
                <el-button size="small" v-else @click="handleUploadLogo">上传图标</el-button>
              </div>
              <span class="form-item-des">建议尺寸16x16的.ico格式图标</span>
            </div>
          </el-form-item>
          <el-form-item label="站点标题" prop="title">
            <el-input v-model="siteForm.title" placeholder="输入站点标题" />
          </el-form-item>
          <el-form-item label="站点描述" prop="description">
            <el-input v-model="siteForm.description" type="textarea" :autosize="{ minRows: 3 }" :min="3" placeholder="针对搜索引警设置的网页描述，一般不超过200字符" />
          </el-form-item>
          <el-form-item label="关键字" prop="keywords">
            <el-input v-model="siteForm.keywords" type="textarea" :autosize="{ minRows: 3 }" :min="3" placeholder="关键字中间用半角逗号隔开" />
          </el-form-item>
          <el-form-item label="主题色" prop="themeColor">
            <el-color-picker v-model="siteForm.themeColor" />
          </el-form-item>
          <el-form-item label="百度统计id" prop="setting.statisticId">
            <el-input v-model="siteForm.setting.statisticId" placeholder="输入百度统计id" />
          </el-form-item>
          <el-form-item label="图片最大宽度" prop="setting.maxWidth">
            <el-input-number v-model="siteForm.setting.maxWidth" placeholder="输入站点下文章图片上传宽度限制" type="number" :min="0" />
            像素（px）
          </el-form-item>
          <el-form-item label="视频最大体积" prop="setting.maxSize">
            <el-input-number v-model="siteForm.setting.maxSize" placeholder="输入站点下文章图片上传宽度限制" type="number" :min="0" />
            体积（MB）
          </el-form-item>
          <el-form-item label="允许视频格式" prop="setting.ext">
            <el-input v-model="siteForm.setting.ext" placeholder="输入允许上传的视频格式，多种格式用 | 分割" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <div class="right-btn">
            <el-button type="primary" @click="submitSiteForm">确认</el-button>
            <el-button @click="isShowForm = false">关闭</el-button>
          </div>
        </span>
      </template>
    </el-dialog>
    <ImageUpload v-model:showDialog="showImgUpload" allow=".ico" :limit="1" @getImage="getImage"></ImageUpload>
    <!-- 站点置灰 -->
    <el-dialog v-model="ashDialog" title="站点置灰" width="500px" @close="ashDialogClose">
      <el-form label-width="70px" label-position="right">
        <el-form-item label="置灰时间">
          <el-date-picker
            v-model="ashTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="defaultAshTimeRange"
            value-format="x"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ashDialog = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmAsh">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { insertSite, updateSite, deleteSite, siteAsh, siteAshRecover, updateSiteState } from '@/api/site'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Link, Clock, Cpu } from '@element-plus/icons-vue'
import { hasPermission } from '@ruifox-cms/utils'
import BaseInfo from './components/BaseInfo.vue'
import dayjs from 'dayjs'

const store = useStore()
const router = useRouter()
const showCard = ref(true)
/******************************************************卡片模式********************************************* */
const currentTabIndex = ref(0) // 当前tab索引
const currentTabInfo = computed(() => siteList.value[currentTabIndex.value]) // 当前tab信息
const currentMoreTabName = ref('base') // 当前更多信息区域的tab
const editPopoverRef = ref(null) // 编辑站点名称弹窗
const currentSiteName = ref('') // 当前站点名称
const handleEditSiteName = async () => {
  if (!currentSiteName.value) {
    ElMessage.error('请输入站点名称')
    return
  }
  const res = await updateSite({ id: currentTabInfo.value.id, name: currentSiteName.value })
  if (res.code === 20000) {
    ElMessage.success('更新成功')
    handleGetSiteList()
  }
}

const handlePopShow = () => {
  currentSiteName.value = currentTabInfo.value.name
}
const handlePopHide = () => {
  currentSiteName.value = ''
}

const handleOpenSite = () => {
  window.open(currentTabInfo.value.domain + currentTabInfo.value.uri, '_blank')
}

/******************************************************列表模式********************************************* */
// 站点列表字段
const fieldList = ref([
  { title: '站点名称', name: 'name' },
  { title: '站点链接', name: 'url' },
  { title: '站点图标', name: 'logo' },
  { title: '状态', name: 'state' },
  { title: '是否置灰', name: 'isAsh' },
  { title: '创建时间', name: 'createTime' },
  { title: '更新时间', name: 'updateTime' },
  { title: '操作', name: 'options' }
])

/******************************************************通用逻辑********************************************* */
const siteStatus = ref([
  { value: 1, label: '已关停' },
  { value: 0, label: '运行中' }
])

// 站点列表
const siteList = ref(store.state.site.siteGroup)
const siteListLoading = ref(false)
const handleGetSiteList = async () => {
  siteListLoading.value = true
  siteList.value = await store.dispatch('site/updateSiteGroup')
  siteListLoading.value = false
}
handleGetSiteList()

// 添加站点
const siteDefaultForm = {
  name: '',
  domain: '',
  uri: '',
  title: '',
  description: '',
  keywords: '',
  themeColor: '',
  setting: {
    statisticId: '',
    maxWidth: 2000,
    maxSize: 1024,
    ext: '3gp|asf|avi|dat|dv|flv|f4v|m2t|m3u8|m4v|mj2|mjpeg|mkv|mov|mp4|mpe|mpg|mpeg|mts|ogg|qt|rm|rmvb|swf|ts|vob|wmv|webm|acc|ac3|acm|amr|ape|caf|flac|m4a|mp3|ra|wav|wma'
  },
  logo: ''
}
const siteFormRules = reactive({
  name: [{ required: true, message: '请填写站点名称', trigger: 'blur' }],
  domain: [{ required: true, message: '请填写静态域名', trigger: 'blur' }]
})
const siteForm = reactive(Object.assign({}, siteDefaultForm))
const isShowForm = ref(false)
const siteFormRef = ref(null)
const handleAddSite = () => {
  isShowForm.value = true
}
const submitSiteForm = () => {
  siteFormRef.value.validate(async valid => {
    if (valid) {
      if (siteForm.id) {
        const res = await updateSite(siteForm)
        if (res.code === 20000) {
          ElMessage.success('更新成功')
          handleGetSiteList()
          isShowForm.value = false
        }
      } else {
        const res = await insertSite(siteForm)
        if (res.code === 20000) {
          ElMessage.success('添加成功')
          handleGetSiteList()
          isShowForm.value = false
        }
      }
    }
  })
}

// 编辑站点
const handleEditSite = row => {
  if (!row.setting) {
    row.setting = {}
  }
  Object.assign(siteForm, row)
  isShowForm.value = true
}

// logo上传
const showImgUpload = ref(false)
const handleUploadLogo = () => {
  showImgUpload.value = true
}
const getImage = data => {
  siteForm.logo = data[0].url
}

// 弹窗关闭恢复默认
const siteDialogClose = () => {
  siteFormRef.value.resetFields()
  Object.assign(siteForm, siteDefaultForm)
  delete siteForm.id
}

// 站点置灰
const ashDialog = ref(false)
const ashTimeRange = ref(null)
const defaultAshTimeRange = ref(null)
const ashForm = ref({})
const handleAshSite = row => {
  defaultAshTimeRange.value = [dayjs(), dayjs().add(1, 'day')]
  ashForm.value.id = row.id
  ashForm.value.isAsh = !row.isAsh
  ashDialog.value = true
}
const handleConfirmAsh = async () => {
  if (!ashTimeRange.value) {
    ElMessage.error('请选择时间范围')
    return
  }
  ashForm.value.ashTime = ashTimeRange.value[0]
  ashForm.value.recoverTime = ashTimeRange.value[1]
  const res = await siteAsh(ashForm.value)
  if (res.code === 20000) {
    ashDialog.value = false
    handleGetSiteList()
  }
}
const ashDialogClose = () => {
  ashTimeRange.value = null
  ashForm.value = {}
}

// 取消置灰
const handleUnAshSite = async row => {
  const res = await siteAshRecover({ id: row.id })
  if (res.code === 20000) {
    ElMessage.success('取消成功')
    handleGetSiteList()
  }
}

// 启用/关停站点
const handleUpdateState = async state => {
  const res = await updateSiteState({ id: currentTabInfo.value.id, state })
  if (res.code === 20000) {
    ElMessage.success('更新成功')
    handleGetSiteList()
  }
}

// 删除站点
const handleDeleteSite = row => {
  ElMessageBox.confirm('此操作将永久删除该站点, 是否继续?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(() => {
      deleteSite({ id: row.id }).then(res => {
        if (res.code === 20000) {
          ElMessage.success('删除成功')
          handleGetSiteList()
        }
      })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 进入当前站点的建设中心
const goSiteBuild = site => {
  if (store.state.site.currentSite.id != site.id) {
    ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">前往该建设中心需切换当前站点，是否继续？</div>', '操作确认', {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    }).then(() => {
      store.commit('site/SET_CURRENT_SITE', site)
      store.commit('category/SET_SITE_CATEGORY_TREE', {siteId: site.id})
      goRouter('/build/category/list')
    })
  } else {
    goRouter('/build/category/list')
  }
}

// 功能页面跳转
const goRouter = path => {
  if (!path) return
  router.push({ path })
}
</script>
<style scoped lang="scss">
.site-overview {
  .site-add {
    display: flex;
    justify-content: flex-end;
    .change-card {
      height: 32px;
      width: 64px;
      box-sizing: border-box;
      border: var(--el-border);
      border-radius: 4px;
      display: flex;
      overflow: hidden;
      margin: 0 20px;
      a {
        display: flex;
        width: 50%;
        height: 100%;
        align-items: center;
        justify-content: center;
      }
      a.active {
        background-color: $mainColor;
        i {
          color: #fff;
        }
      }
    }
  }
  .site-card {
    .overview-info {
      width: 100%;
      background-color: #fff;
      .overview-info-card {
        padding: 16px;
        border: 1px solid #e5e5e5;
        border-radius: 4px;
        overflow: hidden;
        background: url('~@/assets/site-card-bg.gif') no-repeat center center;
        background-size: cover;
        &:hover {
          box-shadow: 1px 1px 4px 0 #00000021;
        }
        .row1 {
          display: flex;
          align-items: end;
          .site-name {
            margin-right: 8px;
            font-size: 20px;
            font-weight: 500;
            color: #333;
          }
          .site-status {
            margin-left: 20px;
            .site-status-tag {
              padding: 4px 8px;
              border-radius: 4px;
              font-size: 14px;
              color: #fff;
              &.tag-1 {
                background-color: #ff5240;
              }
              &.tag-0 {
                background-color: #2cbf77;
              }
            }
          }
        }
        .row2 {
          display: flex;
          align-items: center;
          margin-top: 4px;
          font-size: 14px;
          color: #666;
          &:hover {
            color: $mainColor;
          }
          .site-url {
            margin-right: 6px;
            cursor: pointer;
          }
          .site-url-icon {
            cursor: pointer;
          }
        }
        .row3 {
          margin-top: 20px;
          display: flex;
          .row3-left {
            flex: 1;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
            .site-info-item {
              display: flex;
              align-items: center;
              font-size: 14px;
              .label {
                color: #333;
                margin: 0 4px;
              }
              .value {
                color: #555;
              }
            }
          }
          .row3-divider {
            margin: 0 32px;
            width: 1px;
            height: 62px;
            background-color: #0000000f;
          }
          .row3-right {
            flex: 1;
          }
        }
        .row4 {
          margin-top: 20px;
        }
      }
    }
    .more-info {
      margin-top: 20px;
      width: 100%;
    }
  }
  .site-list {
    margin-top: 10px;
  }
}

.site-dialog {
  .site-ico-box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .site-ico {
      width: 16px;
      height: 16px;
      margin-right: 5px;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .el-button {
      margin-top: 10px;
    }
  }
}
</style>
